/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "lu_bleNet.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
//#include "cJSON.h"

#include "esp_log.h"
//---------------------pan-------
#include "pan_main.h"

static const char *TAG = "APP_MAIN";
APP_INFO app_info;
APP_INFO ver_info;
#define deveice_type "10005"

char SOFT_AP_SSID[20] = "BEWATEC";
char Default_Version[3] = {1, 0, 0};
uint8_t macaddress[6];
char lastwill_topic[80];
char ota_progress_topic[80];
char calibration_topic[90];
char health_topic[90];
char firmware_topic[80];
char publish_topic[80];
char subscribe_topic[80];
char press_topic[80];//压力垫数据
char humanbody_topic[80];//身高体重数据
char config_topic[80];//身高体重数据
char mqtt_upload_data[100];
xQueueHandle start_OTA_queue = NULL;

void app_main(void)
{
    esp_log_level_set("*", ESP_LOG_INFO);

    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    uart_init();

    // esp_read_mac(app_info.macAddr,ESP_MAC_WIFI_STA);
    esp_read_mac(macaddress, ESP_MAC_WIFI_STA);

    //读取配网信息
    size_t length = 0;
    size_t ver_length = 0;
    // 读取保存数据
    user_nvs_read_blob(NVS_APP_INFO, NULL, &length);
    user_nvs_read_blob(NVS_VER_INFO, NULL, &ver_length);

    if (0 == length)
    {
        ESP_LOGI(TAG, "Nothing saved yet!\n");
    }
    else
    {
        // length=sizeof(app_info);
        // 判断版本有没有存储,没有就赋值默认值
        if (ver_length == 0)
        {
            ESP_LOGI(TAG, "Current Version is No saved yet!\n");
            memcpy(&ver_info.version, Default_Version, 3);
        }
        else
        {
            user_nvs_read_blob(NVS_VER_INFO, &ver_info, &ver_length);
        }
        user_nvs_read_blob(NVS_APP_INFO, &app_info, &length);
        ESP_LOGI(TAG, "sizeof(app_info): %d", sizeof(app_info));
        ESP_LOGI(TAG, "password: %s", app_info.password);
        ESP_LOGI(TAG, "SerialNumber: %s", app_info.SerialNumber);
        ESP_LOGI(TAG, "SSID: %s", app_info.ssid);
        ESP_LOGI(TAG, "serverIP: %s", app_info.server_ip);
        ESP_LOGI(TAG, "serverPort: %d", app_info.port);
        ESP_LOGI(TAG, "version: %d:%d:%d", ver_info.version[0], ver_info.version[1], ver_info.version[2]);
        ESP_LOGI(TAG, "mattversion: %d:%d:%d:%d", ver_info.mattress_version[0], ver_info.mattress_version[1],
                 ver_info.mattress_version[2], ver_info.mattress_version[3]);
    }
    //--------------------判断是否配网----------------------------------------
    if ((app_info.ssid != NULL) && (app_info.ssid[0] != 0xff) && (app_info.ssid[0] != 0x00))//wifi名
    {
        //------------上发后台主题--------------------
        //拼接发送主题
        // sprintf(publish_topic,"iot/bytes/dest/backend/src/device/type/%s/uri/%s/tag/data",deveice_type,app_info.SerialNumber);
        sprintf(publish_topic, "iot/up/type/%s/uri/%s/data", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "publish topic: %s", publish_topic);
        //拼接时间校准主题
        // sprintf(calibration_topic,"iot/bytes/dest/backend/src/device/type/%s/uri/%s/tag/calib",deveice_type,app_info.SerialNumber);
        sprintf(calibration_topic, "iot/up/type/%s/uri/%s/calibration", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "calibration_topic: %s", calibration_topic);
        //拼接固件升级主题
        // sprintf(firmware_topic,"iot/bytes/dest/backend/src/device/type/%s/uri/%s/tag/ota",deveice_type,app_info.SerialNumber);
        sprintf(firmware_topic, "iot/up/type/%s/uri/%s/ota", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "firmware_topic: %s", firmware_topic);
        //遗嘱主题
        // sprintf(lastwill_topic,"iot/bytes/dest/backend/src/device/type/%s/uri/%s/tag/state",deveice_type,app_info.SerialNumber);
        sprintf(lastwill_topic, "iot/up/type/%s/uri/%s/state", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "lastwill_topic:%s", lastwill_topic);
        //设备健康主题
        sprintf(health_topic, "iot/up/type/%s/uri/%s/health", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "health_topic:%s", health_topic);
        //OTA进度主题
        sprintf(ota_progress_topic, "iot/up/type/%s/uri/%s/ota_progress", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "ota_progress_topic:%s", ota_progress_topic);
        //press主题
        sprintf(press_topic, "iot/up/type/%s/uri/%s/press", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "press_topic: %s", press_topic);
        //config主题
        sprintf(config_topic, "iot/up/type/%s/uri/%s/config", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "config_topic: %s", config_topic);
        //身高体重主题
        sprintf(humanbody_topic, "iot/up/type/%s/uri/%s/humanbody", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "humanbody_topic: %s", humanbody_topic);

        //------------后台下发主题--------------------
        //接收主题
        // sprintf(subscribe_topic,"iot/bytes/dest/device/type/%s/uri/%s/src/backend/tag/+",deveice_type,app_info.SerialNumber);
        sprintf(subscribe_topic, "iot/down/type/%s/uri/%s/#", deveice_type, app_info.SerialNumber);
        ESP_LOGI(TAG, "subscribe topic: %s", subscribe_topic);

        xTaskCreate(wifi_init_sta, "wifi_init_sta", 4096, NULL, 5, NULL);
        start_OTA_queue = xQueueCreate(1, 500);
        xTaskCreate(app_http_task, "app_http_task", 8192, NULL, 3, NULL);
    }
    else
    {
        if ((app_info.SerialNumber[0] != 0x00) && (app_info.SerialNumber[0] != 0xff))
        {
            SOFT_AP_SSID[0] = 'B';
            SOFT_AP_SSID[1] = 'W';
            memcpy(&SOFT_AP_SSID[2], app_info.SerialNumber, 12);
            ESP_LOGI(TAG, "SerialNumber:%s \n", app_info.SerialNumber);
        }
        sendData("\xA5\x5A\x02\x00\x0C\x01", 6); //开始配网
         //wifi_init_softap();
         //xTaskCreate(create_ap_server, "ap_server", 4096, (void *)AF_INET, 5, NULL);
        app_BLE_ConnectNet();
    }
}
